package recognitionModule;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

import java.util.Base64.Encoder;

/**
 * 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
 * 
 * @param imgFile
 *            图片本地路径/ imgURL 图片线上路径
 * @return Base64编码过的字节数组字符串
 * @author 王浩博
 */

public class GetBase64 {

	public static String ImageToBase64ByLocal(String imgFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理

		InputStream in = null;
		byte[] data = null;

		// 读取图片字节数组
		try {
			in = new FileInputStream(imgFile);

			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 对字节数组Base64编码
		/*
		 * BASE64Encoder encoder = new BASE64Encoder();
		 * 
		 * return encoder.encode(data);// 返回Base64编码过的字节数组字符串
		 */
		Encoder encoder = Base64.getEncoder();
		String encode = encoder.encodeToString(data);
		return encode;
	}

	public static String ImageToBase64ByOnline(String imgURL) {
		ByteArrayOutputStream data = new ByteArrayOutputStream();
		try {
			// 创建URL
			URL url = new URL(imgURL);
			byte[] by = new byte[1024];
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5000);
			InputStream is = conn.getInputStream();
			// 将内容读取内存中
			int len = -1;
			while ((len = is.read(by)) != -1) {
				data.write(by, 0, len);
			}
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 对字节数组Base64编码
		/*
		 * BASE64Encoder encoder = new BASE64Encoder(); return
		 * encoder.encode(data.toByteArray());
		 */
		Encoder encoder = Base64.getEncoder();
		String encode = encoder.encodeToString(data.toByteArray());
		return encode;
	}
}
